package com.tyl.controller;

import com.tyl.entity.RequestMessage;
import com.tyl.entity.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@ResponseBody
@RequestMapping("/websocket")
public class WsController {

    private SimpMessagingTemplate simpMessagingTemplate;
    @RequestMapping("/index")
    public String test(){
        return "index.html";
    }

    @Autowired
    public WsController(SimpMessagingTemplate simpMessagingTemplate){
        this.simpMessagingTemplate=simpMessagingTemplate;
    }

    @MessageMapping("/welcome")
    @SendTo("/topic/say")
    public ResponseMessage say(RequestMessage message){
        System.out.println(message.getName());
        return new ResponseMessage("welcome,"+message.getName()+"!");
    }

    @Scheduled(fixedDelay = 1000)
    public void callback(){
        SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpMessagingTemplate.convertAndSend("/topic/callback"+"定时推送消息时间"+SDF.format(new Date()));
    }
}
